// pages/select_community/select_community.js
import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast"
import Dialog from "../../miniprogram_npm/@vant/weapp/dialog/dialog"
const app = getApp()
const log = new app.appLogs()
const http = new app.appHttp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    theme: {},
    list: [],
    //当前社区
    community: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "选择社区"
    })
    this.setData({
      theme: app.globalData.theme
    })
    this.getCommunityList()
  },

  /**
   * 获取社区列表
   */
  getCommunityList: function () {
    http.get("area/open/lower",{
      area_code: "86.51.01.16.03",
      // area_code: app.globalData.areaCode
    }).then(res => {
      if (res.data.code === http.REQUEST_OK) {
        let list = []
        res.data.data.forEach(item => {
          item.isSelect = false
          list.push(item)
        })
        this.setData({
          list: list
        })
      }else {
        Dialog.alert({
          title: "错误提示",
          message: "获取社区列表失败\n" + res.data.msg
        }).then(() => {})
      }
    }, err => {
      Dialog.alert({
        title: "错误提示",
        message: "获取社区列表失败，网络异常"
      }).then(() => {})
    })
  },

  /**
   * 选择社区
   * @param e
   */
  onSelect: function (e) {
    const index = e.currentTarget.dataset.index
    this.data.list.forEach((item,i) => {
      this.data.list[i].isSelect = false
    })
    this.data.list[index].isSelect = true
    this.data.community = this.data.list[index]
    this.setData({
      list: this.data.list
    })
  },

  /**
   * 确定
   * @param e
   */
  onDetermine: function (e) {
    if (this.data.community == null) {
      Dialog.alert({
        title: '温馨提示',
        message: '请选择社区',
      }).then(() => {});
    }else {
      app.globalData.areaCode = this.data.community.area_code
      app.globalData.unitCode = this.data.community.unit_code
      app.globalData.appTitle = this.data.community.area_name
      //保存选择的社区信息
      app.saveCommunity(this.data.community.area_name,this.data.community.area_code,this.data.community.unit_code)
      //埋点
      http.postJson("user/area/associate", {
        user_id: app.globalData.userInfo == null ? '' : app.globalData.userInfo.applet_user_id,
        area_code: app.globalData.areaCode
      }).then(res => { }, err => { })
      //跳转界面
      wx.switchTab({
        url: "/pages/index/index"
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})